package com.cx.concurrent;

import java.util.concurrent.TimeUnit;

/**
 * Author:CHENXIAOYI
 * Since:2020/9/22 14:32
 */
public class DclTest {

    private DclTest() {
    }

    private static volatile DclTest instince;

    public static DclTest getInstance(){
        if(instince == null){
            synchronized (DclTest.class){
                if(instince == null){
                    /* 创建对象三个步骤
                     1.分配堆内存空间
                     2.初始化对象
                     3.将堆内存地址指向对象引用
                     若指令重排将 3 放在2 前面 那么其他线程在判断 myInstance == null 时就不成立
                     */
                    instince = new DclTest();
                }
            }
        }
        return instince;
    }



    public static void main(String[] args) throws InterruptedException {

        DclTest instance = DclTest.getInstance();

        Thread a = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(0);
                instance.store(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A");

        Thread b = new Thread(() -> {
            System.out.println(instance.load());
        }, "B");

        a.start();
        b.start();

    }

    private   int i;

    private  int load(){
        return i;
    }

    private  void store(int j){
        i = j;
    }

}
